/*
 * Project: Bearing
 * Copyright (C) 2009 ralfoide gmail com,
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.alfray.bearing.pub.ui;


import com.alfray.bearing.R;
import com.alfray.bearing.core.app.BearingAppImpl;
import com.alfray.bearing.pub.app.BearingApp;
import com.alfray.bearing.pub.app.GpsService;
import com.alfray.bearing.pub.app.GpsService.GpsBinder;
import com.alfray.bearing.pub.app.GpsService.GpsServiceListener;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ToggleButton;

public class CompassActivity extends Activity {

    public static String TAG = CompassActivity.class.getSimpleName();
    private static boolean DEBUG = true;

    private ServiceConnection mServiceConnection;
    private GpsBinder mServiceBinder;
    private ToggleButton mBtnToggleGps;
    private CompassView mCompassView;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        showIntro(false);

        setContentView(R.layout.compass);
        mCompassView = (CompassView) findViewById(R.id.compassView);

        setupButtons();
    }

    @Override
    protected void onResume() {
        super.onResume();
        bindToGpsService();
    }

    @Override
    protected void onPause() {
        super.onPause();
        // on pause we unbind but don't stop.
        unbindFromGpsService();
        // TODO stop service if app isn't tracking anything
    }

    // -----

    private void setupButtons() {
        mBtnToggleGps = (ToggleButton) findViewById(R.id.btnToggleGps);
        mBtnToggleGps.setChecked(GpsService.isServiceIsRunning());
        mBtnToggleGps.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    // start & bind
                    bindToGpsService();
                } else {
                    stopGpsService();
                }
            }
        });
    }

    private void showIntro(boolean force) {
        boolean hideControls = force;
        if (!force) {
            BearingAppImpl app = BearingApp.getInstance(this);
            if (app != null &&
                    app.isFirstStart() &&
                    !app.getPrefsValues().isIntroDismissed()) {
                app.setFirstStart(false);
                force = true;
            }
        }

        if (force) {
            Intent i = new Intent(this, IntroActivity.class);
            if (hideControls) i.putExtra(IntroActivity.EXTRA_NO_CONTROLS, true);
            startActivity(i);
        }
    }

    private void bindToGpsService() {
        if (mServiceConnection == null) {
            final GpsServiceListener listener = new GpsService.GpsServiceListener() {
                @Override
                public void onGpsLocChanged(Location location) {
                    if (mCompassView != null) {
                        float bearing = location.getBearing();
                        mCompassView.setNorthAngleDeg(bearing);
                    }
                }
            };

            mServiceConnection = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                    if (DEBUG) Log.d(TAG, "Activity connected to service");
                    mServiceBinder = (GpsBinder) service;
                    mServiceBinder.addServiceListener(listener);

                    // Update UI state
                    mBtnToggleGps.setChecked(GpsService.isServiceIsRunning());
                }

                @Override
                public void onServiceDisconnected(ComponentName name) {
                    if (DEBUG) Log.d(TAG, "Activity disconnected from service");
                    mServiceBinder = null;
                }
            };
        }

        // Start service, so that it doesn't stop when we unbind
        if (DEBUG) Log.d(TAG, "start requested & bind service");
        Intent service = new Intent(this, GpsService.class);
        startService(service);

        // Connect to the service. This should also start it but doing so would
        // stop it when we unbind, thus the explicit startService just before.
        bindService(service,
                mServiceConnection,
                Context.BIND_AUTO_CREATE);
    }

    private void unbindFromGpsService() {
        if (mServiceConnection != null) {
            // TODO if we have no current marked location being tracked, just stop service too

//            if (mServiceBinder == null || !mServiceBinder.isRecording()) {
//                // If not recording, we explicitly stop the service,
//                // otherwise it will stop running and recording.
//                if (DEBUG) Log.d(TAG, "stop service");
//                Intent service = new Intent(this, RecordService.class);
//                stopService(service);
//            } else {
//                Toast.makeText(this, "TrackDay: Still Recording", Toast.LENGTH_LONG).show();
//            }

            if (DEBUG) Log.d(TAG, "unbind service");
            unbindService(mServiceConnection);
            mServiceConnection = null;
        }
    }

    private void stopGpsService() {
        Intent service = new Intent(this, GpsService.class);
        unbindFromGpsService();
        if (DEBUG) Log.d(TAG, "stop service requested");
        stopService(service);
    }

}
